/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.web;

import org.gtugs.domain.Chapter;
import org.gtugs.domain.User;
import org.gtugs.service.ChapterManager;
import org.gtugs.service.CountryManager;
import org.gtugs.service.EventManager;
import org.gtugs.service.security.AppEngineUserService;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.util.AutoPopulatingList;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jasonacooper@google.com (Jason Cooper)
 */
public class UpdateChapterFormController extends SimpleFormController {

  private ChapterManager chapterManager;
  private CountryManager countryManager;
  private EventManager eventManager;

  @Override 
  protected void initBinder(HttpServletRequest request,
      ServletRequestDataBinder binder) throws Exception {
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class,
        true));
  }

  @Override
  @SuppressWarnings("unchecked")
  protected ModelAndView showForm(HttpServletRequest request,
      HttpServletResponse response, BindException errors) {
    Map<String, Object> map = new HashMap<String, Object>();
    String chapterId = request.getParameter("id");
    Map model = errors.getModel();

    AppEngineUserService userService = new AppEngineUserService();
    map.put("userService", userService);
    model.put("model", map);

    Chapter chapter = retrieveChapter(chapterId);

    if (chapter == null) {
      String errorText = "Failed to retrieve chapter with ID \"" + chapterId +
          "\" -- chapter not found.";
      model.put("errorText", errorText);

      return new ModelAndView("admin_error", model);
    }
    if (!hasAccess(userService, chapter)) {
      userService.setAfterLogoutEndpoint("/admin");

      String errorText = "You are not listed as an organizer for this " +
          "chapter. Please sign in with an organizer's account to access " +
          "this page.";
      model.put("errorText", errorText);

      return new ModelAndView("admin_error", model);
    }

    map.put("chapter", chapter);
    map.put("countries", countryManager.getCountries());
    map.put("events", eventManager.getEventsForChapter(chapter.getId()));

    return new ModelAndView(getFormView(), model);
  }

  @Override
  protected Object formBackingObject(HttpServletRequest request) throws
      ServletException {
    Chapter chapter = retrieveChapter(request.getParameter("id"));

    if (chapter == null) {
      return new Chapter();
    } else {
      // Workaround for IndexOutOfBoundsException
      List<User> administrators = new AutoPopulatingList(User.class);
      administrators.addAll(chapter.getAdministrators());
      chapter.setAdministrators(administrators);
    }

    return chapter;
  }

  @Override
  protected void onBind(HttpServletRequest request, Object command)
      throws Exception {
    Chapter chapter = (Chapter) command;
    List<User> administrators = chapter.getAdministrators();

    for (int i = administrators.size() - 1; i >= 0; i--) {
      if (administrators.get(i).getIsFlagged()) {
        administrators.remove(i);
      }
    }
  }

  @Override
  public ModelAndView onSubmit(Object command) throws ServletException {
    Chapter cmd = (Chapter) command;
    Chapter chapter = retrieveChapter(cmd.getId());
    AppEngineUserService userService = new AppEngineUserService();

    if (chapter == null) {
      String errorText = "Failed to update chapter with ID \"" + cmd.getId() + 
          "\" -- chapter not found.";

      return new ModelAndView("admin_error", "errorText", errorText);
    }
    if (!hasAccess(userService, chapter)) {
      String errorText = "You are not listed as an organizer for this " +
          "chapter. Please sign in with an organizer's account to access " +
          "this page.";

      return new ModelAndView("error", "errorText", errorText);
    }

    chapter.setName(cmd.getName());
    chapter.setType(cmd.getType());
    chapter.setCity(cmd.getCity());
    chapter.setState(cmd.getState());
    chapter.setCountry(cmd.getCountry());
    chapter.setStatus(cmd.getStatus());
    chapter.setLatitude(cmd.getLatitude());
    chapter.setLongitude(cmd.getLongitude());
    chapter.setWebsite(cmd.getWebsite());
    chapter.setMeetupGroupUrlName(cmd.getMeetupGroupUrlName());
    chapter.setMailingList(cmd.getMailingList());
    chapter.setAdministrators(cmd.getAdministrators());
    chapter.setDescription(cmd.getDescription());
    chapterManager.storeChapter(chapter);

    return new ModelAndView(new RedirectView(getSuccessView()));
  }

  public void setChapterManager(ChapterManager chapterManager) {
    this.chapterManager = chapterManager;
  }

  public void setCountryManager(CountryManager countryManager) {
    this.countryManager = countryManager;
  }

  public void setEventManager(EventManager eventManager) {
    this.eventManager = eventManager;
  }

  private Chapter retrieveChapter(String idString) {
    Long id = null;

    try {
      id = Long.parseLong(idString);
    } catch (NumberFormatException ex) {
      return null;
    }

    return retrieveChapter(id);
  }

  private Chapter retrieveChapter(Long id) {
    return chapterManager.getChapter(id);
  }

  private boolean hasAccess(AppEngineUserService userService, Chapter
      chapter) {
    if (userService.isUserAdmin()) {
      return true;
    }

    User user = userService.getUser();
    for (User administrator : chapter.getAdministrators()) {
      if (administrator.getEmail().equalsIgnoreCase(user.getEmail())) {
        return true;
      }
    }

    return false;
  }
}
